<template>
  <div style="position: relative;">
    <div style="width: 100%; height: 100%;" v-html="videoHtml">
    </div>
    <div style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;" @click="$emit('click')">
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import request from '@/utils/request4screen'
  Vue.prototype.$http = request // ajax请求方法

  import videojs from 'video.js'
  import "videojs-flash"
  import "video.js/dist/video-js.min.css"
  export default {
    name: "videojsPlayer",
    props: {
      // 播放流格式
      protocol: {
        type: String,
        default: 'hls'  // rtmp  hls
      },
      // 取流平台
      platform: {
        type: String,
        default: 'icm'  // icm isc
      },
      streamType: {
        type: Number,   // 0 是主码流，视频大，  1是子码流，适合画面小的
        default: 1
      },
      // 这个如果有数据 source自动失效，多个用，分割 针对于海康平台取rtmp流播放
      cameraIndexCode: {
        type: String,
        default: ''
      },
      // 每个视频播放的时间 单位秒， 0表示不轮播 针对于海康平台取rtmp流播放
      speed: {
        type: Number,
        default: 240
      },
      // 计数最大次数，5次请求不成功，则进行下一个 针对于海康平台取流播放
      conutMax: {
        type: Number,
        default: 5
      }
    },
    data() {
      return {
        playerId: '',
        player: null,
        videoHtml: '',
        playCameraIndex: -1,
        cameraIndexCodes: [],
        timerReq: null,
        conutReq: 0,  // 用于计数，5次请求不成功，则进行下一个
        timerReplay: null
      }
    },
    mounted() {
      console.log('mounted')
      this.cameraIndexCodes = this.cameraIndexCode.split(',')
      this.playerId = 'videojsplayer_' + Math.random().toString(36).substr(2)
      this.videoHtml = '<video id="'+this.playerId+'" class="video-js" poster="loading.jpg"></video> '
      setTimeout(() => {
        if (this.cameraIndexCodes.length > 0) {
          this.playCameraIndex = 0
          this.playVideo()
        }
      }, 500)
    },
    beforeDestroy() {
      console.log( 'beforeDestroy' )
      // 清理下定时器
      if(this.timerReplay) {
        clearInterval(this.timerReplay)
        this.timerReplay = null
      }
      if(this.timerReq) {
        clearInterval(this.timerReq)
        this.timerReq = null
      }
      if(this.player) {
        this.player.dispose()
        this.player = null
      }
    },
    watch: {
      cameraIndexCode (val) {
        this.cameraIndexCodes = val.split(',')
        // 清理下定时器
        if(this.timerReplay) {
          clearInterval(this.timerReplay)
          this.timerReplay = null
        }
        if(this.timerReq) {
          clearInterval(this.timerReq)
          this.timerReq = null
        }
        if (this.cameraIndexCodes.length > 0) {
          this.playCameraIndex = 0
          this.playVideo()
        } else {
          if(this.player) {
            this.player.reset()
            this.player.pause()
          }
        }
      }
    },
    methods: {
      replay (source, type) {
        console.log('开始播放视频源：' + source + ' playerId:'+this.playerId)
        this.player= videojs(this.playerId, {
          muted: true,
          // controls: true,
          autoplay: true
        })
        this.player.src({
          src: source,
          type: type
        })
        this.player.volume(0)
        // 清理下定时器
        if(this.timerReplay) {
          clearInterval(this.timerReplay)
          this.timerReplay = null
        }
        if (this.cameraIndexCodes.length > 0) {
          this.timerReplay = setTimeout(()=>{
            this.playVideo()
          }, this.speed * 1000)
        }
      },
      playVideo () {
        if (this.cameraIndexCodes.length == 0) {
          return
        }
        if(this.playCameraIndex == -1) {
          this.playCameraIndex = 0
        }
        if(this.playCameraIndex >= this.cameraIndexCodes.length ) {
          this.playCameraIndex = 0
        }
        var cameraIndexCode = this.cameraIndexCodes[this.playCameraIndex]
        this.conutReq = 0
        this.getUrl(cameraIndexCode, (sourceUrl, type)=>{
          console.log("type:"+type)
          console.log("sourceUrl:"+sourceUrl)
          if(!sourceUrl) {
            this.playVideo()
          } else {
            this.replay(sourceUrl, type)
          }
        })
        this.playCameraIndex++
      },
      getUrl (cameraIndexCode, callback) {
        // console.log(cameraIndexCode)
        // callback('http://ivi.bupt.edu.cn/hls/cctv10.m3u8', 'application/x-mpegURL')
        var self = this
        this.conutReq ++
        if(this.conutReq > this.conutMax) {
          callback()
          return
        }
        // 清理下定时器
        if(this.timerReq) {
          clearInterval(this.timerReq)
          this.timerReq = null
        }
        console.log('打印日志')
        // 获取海康平台视频流
        this.$http({
          url: 'http://10.242.182.32/wpt/api/hikvision/'+this.platform,
          method: 'post',
          params: {
            url: '/api/video/v1/cameras/previewURLs',
            param: {
              cameraIndexCode: cameraIndexCode,
              streamType: this.streamType,   // 0 是主码流，视频大，  1是子码流，适合画面小的
              protocol: this.protocol,
              transmode: 1,
              expand: 'transcode=0'
            }
          }
        }).then((data) => {
          // on failure: {"code":0,"success":false}
          console.log("video data: "+ JSON.stringify(data))

          if (data && data.success && data.data) {
            var hikdata = JSON.parse(data.data)
            if (hikdata.code === '0'){
              var url = hikdata.data.url
              // if(hikdata.data.url != null) {
              //   url = hikdata.data.url.replace('192.168.20.243', '172.30.24.121')
              // }
              // 城运的大屏和我的向日葵PC 在同一个网络
              // if (url && window.location.href.indexOf("10.242")) {
              //   url = url.replace('192.168.20.243','172.30.24.121')
              // }
              if(this.protocol === 'rtmp') {
                callback(url+'/', 'rtmp/flv')
              } else if(this.protocol === 'hls'){
                callback(url, 'application/x-mpegURL')
              }
            } else {
              this.timerReq = setTimeout(()=>{
                self.getUrl(cameraIndexCode, callback)
              }, 5000)
            }
          } else {
            this.timerReq = setTimeout(()=>{
              self.getUrl(cameraIndexCode, callback)
            }, 5000)
          }
        }).catch((err)=>{

          // on failure: {"code":0,"success":false}
          console.log(" video catch ")
          console.log(err)
          console.log("video err: "+ JSON.stringify(err))
        })
      }
    }
  }
</script>
<style>
  .video-js{
    width: 100%;
    height: 100%;
  }
</style>
